package com.td.erhome.ui.min;

import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.td.erhome.R;
import com.td.erhome.base.BaseActivity;
import com.td.erhome.models.BaseBean;
import com.td.erhome.models.CiyiInfoBean;
import com.td.erhome.models.User;
import com.td.erhome.net.Api;
import com.td.erhome.net.BaseSubscriber;
import com.td.erhome.utils.ConstUtils;
import com.td.erhome.utils.DialogUtils;
import com.td.erhome.utils.ImageLoader;
import com.td.erhome.utils.RxBus;
import com.td.erhome.utils.T;
import com.td.erhome.utils.TextUtil;
import com.td.erhome.utils.TypeUtils;
import com.td.erhome.utils.UserManager;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

//我的个人信息
public class MyMessageActivity extends BaseActivity {

    @Bind(R.id.img_go)
    ImageView mImgGo;
    @Bind(R.id.img_header)
    ImageView mImgHeader;
    @Bind(R.id.re_img_selector)
    RelativeLayout mReImgSelector;
    @Bind(R.id.et_name)
    EditText mEtName;
    @Bind(R.id.tv_sex)
    TextView mTvSex;
    @Bind(R.id.et_sfz)
    EditText mEtSfz;
    @Bind(R.id.et_phone)
    EditText mEtPhone;
    @Bind(R.id.et_wxh)
    EditText mEtWxh;
    @Bind(R.id.et_address)
    TextView mEtAddress;
    @Bind(R.id.tv_sure)
    TextView mTvSure;
    @Bind(R.id.tv_sex_et)
    TextView mTvSexEt;
    @Bind(R.id.td_back)
    ImageView mTdBack;
    @Bind(R.id.lin_sex)
    LinearLayout mLinSex;
    @Bind(R.id.et_de_address)
    EditText mEtDeAddress;
    @Bind(R.id.tv_logout)
    TextView mTvLogout;
    private ArrayList<String> paths = new ArrayList<>(); //放图片
    private List<String> mStringList = new ArrayList<>();
    private Subscription mSubscribe;
    private long mArea_id;
    private DialogUtils mDialogUtils;
    final List<File> fileList = new ArrayList<>();
    final List<RequestBody> requestBodies = new ArrayList<>();
    private CiyiInfoBean mCiyiInfoBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_message;
    }
    @Override
    protected void initView() {
        ImageLoader.loadCicleImage(this, UserManager.getIns().getUser().head_img,R.mipmap.td_min_tx,mImgHeader);
        mEtName.setText(UserManager.getIns().getUser().true_name);
        mTvSexEt.setText(TypeUtils.getSexString(UserManager.getIns().getUser().sex));
        mEtSfz.setText(UserManager.getIns().getUser().id_card);
        mEtPhone.setText(UserManager.getIns().getUser().mobile);
        mEtWxh.setText(UserManager.getIns().getUser().wechat_no);
        mEtDeAddress.setText(UserManager.getIns().getUser().address);
        mEtAddress.setText(UserManager.getIns().getUser().area_name+"   "+UserManager.getIns().getUser().street_name);
        mArea_id = UserManager.getIns().getUser().street_id;

        mSubscribe = RxBus.getInstance().toObserverable(CiyiInfoBean.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<CiyiInfoBean>() {
                    @Override
                    public void call(CiyiInfoBean ciyiInfoBean) {
                        mCiyiInfoBean = ciyiInfoBean;
                        mEtAddress.setText(ciyiInfoBean.aeraLitePal.area_name+"   "+ciyiInfoBean.streetLitePal.area_name);
                        mArea_id = ciyiInfoBean.streetLitePal.getArea_id();
                    }
                });

        mDialogUtils = new DialogUtils();
    }

    @Override
    protected void releaseResource() {
        paths = null;
        mStringList = null;
        if (!mSubscribe.isUnsubscribed()){
            mSubscribe.unsubscribe();
        }
    }

    @OnClick({R.id.re_img_selector, R.id.tv_sex, R.id.tv_sure,R.id.lin_sex,R.id.et_address,R.id.td_back,R.id.tv_logout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.re_img_selector:
                PhotoPicker.builder()
                        .setSelected(paths)
                        .setPhotoCount(1)
                        .start(MyMessageActivity.this);

                break;
            case R.id.tv_sex:
                break;
            case R.id.tv_sure:
                if (TextUtil.isEditTextEmpty(mEtName)){
                    T.showLong(this,"请输入用户名");
                    return;
                }
                if (TextUtil.isTextViewEmpty(mTvSexEt)||TypeUtils.getSexInt(mTvSexEt.getText().toString())==0){
                    T.showLong(this,"请选择性别");
                    return;
                }
                if (TextUtil.isEditTextEmpty(mEtSfz)){
                    T.showLong(this,"请输入身份证");
                    return;
                } if (TextUtil.isEditTextEmpty(mEtPhone)){
                    T.showLong(this,"请输入手机号");
                    return;
                } if (TextUtil.isEditTextEmpty(mEtWxh)){
                    T.showLong(this,"请输入微信号");
                    return;
                }if (TextUtil.isTextViewEmpty(mEtAddress)){
                    T.showLong(this,"请选择区域");
                    return;
                }if (TextUtil.isEditTextEmpty(mEtDeAddress)){
                    T.showLong(this,"请输入详细地址");
                    return;
                }
                postData();
                break;
            case R.id.lin_sex:
                mStringList.clear();
                mStringList.add("男");
                mStringList.add("女");
                mDialogUtils.createBottom(this,mStringList,mTvSexEt);
                break;
            case R.id.et_address:
                mDialogUtils.createAddressBottom(this,mEtAddress);
                break;
            case R.id.td_back:
                finish();
                break;
            case R.id.tv_logout:
                logout();
                break;

        }
    }

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK &&
                (requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {
            if (data != null) {
                paths = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                ImageLoader.loadCicleImage(this, paths.get(0), mImgHeader);
                for (int i = 0; i < paths.size(); i++) {
                    compressWithLs(new File(paths.get(i)));
                }

            }
        }
    }


    /**
     * 退出登录
     */
    public void logout(){
        HashMap<String, Object> params = new HashMap<>();
        params.put("user_id", UserManager.getIns().getUser().uid);
        Api.getRetrofit().logoff(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseBean>(MyMessageActivity.this){
                    @Override
                    public void onNext(BaseBean baseBean) {
                        super.onNext(baseBean);
                        UserManager.getIns().clearUserInfo();
                        RxBus.getInstance().post(ConstUtils.LOGOUT);
                        T.showLong(MyMessageActivity.this,"登出成功");
                        finish();
                    }
                });
    }

    /**
     * 压缩单张图片 Listener 方式
     */
    private void compressWithLs(File file) {
        Luban.get(this)
                .load(file)
                .putGear(Luban.THIRD_GEAR)
                .setFilename(System.currentTimeMillis() + "")
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        //   Toast.makeText(MyMessageActivity.this, "I'm start", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(File file) {
                        RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                        fileList.add(file);
                        requestBodies.add(fileBody);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }


    /**
     * 图片上传
     */
                                private void postData() {
                                    MultipartBody boy = null;
                                    if (fileList != null) {
                                        if (fileList.size() == 1) {
                                            boy = new MultipartBody.Builder()
                                                    .setType(MultipartBody.FORM)
                                                    .addFormDataPart("user_id", UserManager.getIns().getUser().uid+"")
                                                    .addFormDataPart("token", UserManager.getIns().getUser().access_token)
                                                    .addFormDataPart("street_id", "510184211")
                                                    .addFormDataPart("true_name", mEtName.getText().toString())
                                                    .addFormDataPart("sex", TypeUtils.getSexInt(mEtName.getText().toString())+"")
                                                    .addFormDataPart("id_card", mEtSfz.getText().toString()+"")
                                                    .addFormDataPart("mobile", mEtPhone.getText().toString()+"")
                                                    .addFormDataPart("wechat_no", mEtWxh.getText().toString()+"")
                                                    .addFormDataPart("address", mEtDeAddress.getText().toString()+"")
                                                    .addFormDataPart("street_id", mArea_id+"")
                                                    .addFormDataPart("head_img", fileList.get(0).getName(), requestBodies.get(0))
                                                    .build();
                                        }else {
                                            boy = new MultipartBody.Builder()
                                                    .setType(MultipartBody.FORM)
                                                    .addFormDataPart("user_id", UserManager.getIns().getUser().uid+"")
                                                    .addFormDataPart("token", UserManager.getIns().getUser().access_token)
                                                    .addFormDataPart("street_id", "510184211")
                                                    .addFormDataPart("true_name", mEtName.getText().toString())
                                                    .addFormDataPart("sex", TypeUtils.getSexInt(mTvSexEt.getText().toString())+"")
                                                    .addFormDataPart("id_card", mEtSfz.getText().toString()+"")
                                                    .addFormDataPart("mobile", mEtPhone.getText().toString()+"")
                                                    .addFormDataPart("wechat_no", mEtWxh.getText().toString()+"")
                                                    .addFormDataPart("address", mEtDeAddress.getText().toString()+"")
                                                    .addFormDataPart("street_id", mArea_id+"")
                                                    .build();
                                        }

                                        Api.getRetrofit().saveProfile(boy)
                                                .subscribeOn(Schedulers.io())
                                                .observeOn(AndroidSchedulers.mainThread())
                                                .subscribe(new BaseSubscriber<BaseBean<User>>(MyMessageActivity.this){
                                                    @Override
                                                    public void onNext(BaseBean<User> userBaseBean) {
                                                        super.onNext(userBaseBean);
                                                        User data = userBaseBean.getData();
                                                        data.access_token = UserManager.getIns().getUser().access_token;
                                                        UserManager.getIns().saveUserInfo(data);
                                                        T.showLong(MyMessageActivity.this,"更新成功");
                                                        RxBus.getInstance().post(ConstUtils.LOGOUT);
                                                        finish();
                                                    }
                                                });
                                    }
                                }

}
